import Topic from '../model/topics'
import User from '../model/users'
import { controller, post, get, patch } from '../decorator'
import { Context } from 'koa'
import { use } from '../decorator/use'
import auth from '../middleware/auth'
import checkTopicExist from '../middleware/checkTopicExist'

@controller('/topics')
export class TopicsController {
  @post('/')
  @use(auth)
  async create(ctx: Context) {
    ctx.verifyParams?.({
      name: { type: 'string', required: true },
      avatar_url: { type: 'string', required: false },
      introduction: { type: 'string', required: false },
    })
    const topic = await new Topic(ctx.request.body).save()
    ctx.body = topic
  }

  @get('/')
  async find(ctx: Context) {
    const { per_page = 10 } = ctx.query
    const page = Math.max(ctx.query.page * 1, 1) - 1
    const perPage = Math.max(per_page * 1, 1)

    ctx.body = await Topic.find({ name: new RegExp(ctx.query.q) })
      .limit(perPage)
      .skip(page * perPage)
  }

  @get('/:id')
  async findById(ctx: Context) {
    const { fields = '' } = ctx.query
    const selectFields = fields
      .split(';')
      .filter((f: string) => f)
      .map((f: string) => ' +' + f)
      .join('')
    const user = await Topic.findById(ctx.params.id).select(selectFields)
    if (!user) {
      ctx.throw(404, '话题不存在')
    }
    ctx.body = user
  }

  @patch('/:id')
  @use(checkTopicExist)
  @use(auth)
  async update(ctx: Context) {
    ctx.verifyParams?.({
      name: { type: 'string', required: false },
      avatar_url: { type: 'string', required: false },
      introduction: { type: 'string', required: false },
    })
    const topic = await Topic.findByIdAndUpdate(ctx.params.id, ctx.request.body)
    ctx.body = topic
  }

  @get('/:id/followers')
  @use(checkTopicExist)
  async listFollowers(ctx:Context) {
    const users = await User.find({ followingTopics: ctx.params.id });
    ctx.body = users;
  }
}
